/**
 * description
 * <p>fill description</p>
 * @author zido
 * @since 2017/6/18 0018
 */
import {post} from '../../../../Util'
export const ADD_SHOP = 'ADD_SHOP'
export const LOAD_DATA = 'BUSINESS_LOAD_DATA'
export const SAVE_FORMS = 'SAVE_FORMS'
export const CHANGE_STEP = 'BUSINESS_CHANGE_STEP'
export const INSERT_BANK_CARD_NAME = 'INSERT_BANK_CARD_NAME'
export const SAVE_FORM_PROPS = 'BUSINESS_SAVE_FORM_PROPS'
export const POST_DATA_TO_BUSINESS = 'POST_DATA_TO_BUSINESS'
export const addShop = () => ({
  type:ADD_SHOP,
})
export const loadData = (id) => {
  return (dispatch) => {
    dispatch({
      type:LOAD_DATA,
      loading:true,
      data:{},
    })
    return post('/api/center/business/get/info?id='+id).then(result => {
      dispatch({
        type:LOAD_DATA,
        loading:false,
        data:result.data,
      })
    })
  }
}
export const postAddData = (data) => {
  return (dispatch) => {
    dispatch({
      type: POST_DATA_TO_BUSINESS,
      postLoading: true,
    })
    return post('/api/center/business/add', data).then(() => {
      dispatch({
        type: POST_DATA_TO_BUSINESS,
        postLoading: false,
      })
    })
  }
}
export const saveForms = (data) => ({
  type:SAVE_FORMS,
  data,
})

export const changeStep = (current) => ({
  type:CHANGE_STEP,
  current:current,
})

export const saveFormProps = (form) => ({
  type:SAVE_FORM_PROPS,
  form:form
})

export const insertBankCardName = (_index,data) => (
  (dispatch,getState) => {
    dispatch({
      type:INSERT_BANK_CARD_NAME,
      bankCardLoading:true,
      bankCardIndex:_index,
    })
    return post('/api/center/business/bankCardCheck?cardNumber='+data.bankCards[_index].bankCardNumber).then(result => {
      const {data} = getState().businessAdd
      dispatch({
        type:INSERT_BANK_CARD_NAME,
        bankCardLoading:false,
        data:{
          ...data,
          bankCards:(()=>{
            data.bankCards.forEach((value,index)=>{
              if(index === _index)
                value.bankName = result.data
            })
            return data.bankCards
          })()
        }
      })
    })
  }
)

export const ACTION_HANDLERS = {
  [ADD_SHOP]:null,
  [LOAD_DATA]:(state,action)=>({...state,...action}),
  [SAVE_FORMS]:(state,action) => ({...state,...action}),
  [CHANGE_STEP]:(state,action) => ({...state,...action}),
  [INSERT_BANK_CARD_NAME]:(state,action) => ({...state,...action}),
  [SAVE_FORM_PROPS]:(state,action) => ({...state,forms:{...state.forms,...action.form}}),
  [POST_DATA_TO_BUSINESS]:(state,action) => ({...state,...action})
}

const initialState = {
  loading:false,
  data:{
    shops:[{}],
    bankCards:[{}],
    user:{},
    businessUser:{},
  },
  current:0,
  bankCardLoading:false,
  bankCardIndex:-1,
}

export default (state = initialState,action) => {
  const handler = ACTION_HANDLERS[action.type]
  return handler ? handler(state, action) : state
}